/********************************************************************************
**  (C) COPYRIGHT 2018 
**	author	:	HuangZiBin
**  E-mail	:	635568706@qq.com
** 	version	:	1.0.1
**	If you find bugs, please contact me.Thank you!
********************************************************************************/
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

#define FILE_NAME "../read_write.c"
#define BUF_SIZE 10000


int read_and_print()
{
	int ret = 0;
	int fd = open(FILE_NAME, O_RDONLY);
	if (fd < 0) {
		fprintf(stderr, "open file %s failed, error:%s\n", FILE_NAME, strerror(errno));
		return -1;
	}
	char data[BUF_SIZE];
	while(1) {
		bzero(data, BUF_SIZE);
		int eof = 0;
		ret = read_file_block(fd, data, BUF_SIZE-1, &eof);
		if (eof > 0) {
			fprintf(stdout, "read file end.\n");
			break;
		}
		if (ret < 0) {
			break;
		}
		fprintf(stdout, "%s", data);
	}
	close(fd);
	return 0;
}


//Write buffer to fd.
//Can be sure that specified number of bytes are worte. Fd can be block or nonblock.
//On success, the function return 1. 
//On error, -1 is returned, and errno is set appropriately.
//If connect closed by peer, 0 is returned.
int write_sure(int fd, unsigned char* buf, int len)
{
	int ret = 0;
	int already_wrote_bytes = 0;
	while(already_wrote_bytes < len) {
		ret = my_write_select(fd, 100);
		if (ret < 0) {
			return ret;
		}
		if (ret == 0) {
			continue;
		}
		ret = write(fd, buf+already_wrote_bytes, len-already_wrote_bytes);
		if (ret < 0 && (errno == EAGAIN || errno == EINTR)) {
			continue;
		}
		if (ret <= 0) {
			return ret;
		}
		already_wrote_bytes += ret;
	}
	return 1;
}


int main()
{
	read_and_print();
	return 0;
}
